
package com.hopechart.micro.common.daemon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.util.ClassUtils;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import java.io.IOException;

/**
 * 任务脚本服务
 *
 * @author daijiang@hopechart.com
 */
public class MicroService {

    private static final Logger log = LoggerFactory.getLogger(MicroService.class);

    public void start(String[] args) throws Exception {
        if (args.length == 0) {
            throw new IllegalStateException("未提供脚本服务应用程序.");
        }
        Class<?> springBootApp = ClassUtils.resolveClassName(args[0],
                MicroService.class.getClassLoader());
        log.info("启动应用程序[{springBootApp.getName()}].");
        SpringApplication.run(springBootApp);
    }

    public void stop(String[] args) throws IOException {
        log.info("关闭应用程序.");
        int jmxPort = Integer.parseInt(args[0]);
        String jmxName = SpringApplicationAdminClient.DEFAULT_OBJECT_NAME;
        JMXConnector connector = SpringApplicationAdminClient.connect(jmxPort);
        try {
            MBeanServerConnection connection = connector.getMBeanServerConnection();
            try {
                new SpringApplicationAdminClient(connection, jmxName).stop();
            } catch (InstanceNotFoundException ex) {
                log.error("未找到 JMX Bean, 无法停止服务.", ex);
                throw new IllegalStateException("未找到 JMX Bean, 无法停止服务.", ex);
            }
        } finally {
            connector.close();
        }
    }

}